// 通用JS工具函数

// 1. 获取当前用户信息
function getCurrentUser() {
    const userStr = localStorage.getItem('gozero_chat_user');
    if (userStr) {
        try {
            return JSON.parse(userStr);
        } catch (e) {
            return null;
        }
    }
    return null;
}

// 2. 全局toast提示
function showToast(message, type = 'success') {
    let toast = document.getElementById('toast');
    if (!toast) {
        toast = document.createElement('div');
        toast.id = 'toast';
        document.body.appendChild(toast);
    } else {
        // 确保 toast 在 body 最后，避免被其它元素遮挡
        if (toast.parentNode !== document.body || document.body.lastChild !== toast) {
            document.body.appendChild(toast);
        }
    }
    toast.className = 'fixed top-6 right-6 z-[9999] px-4 py-2 rounded shadow-lg text-white text-sm transition-all duration-300 ' + (type === 'success' ? 'bg-green-500' : type === 'info' ? 'bg-blue-500' : 'bg-red-500');
    toast.textContent = message;
    toast.style.display = 'block';
    setTimeout(() => { toast.style.display = 'none'; }, 3000);
}

// 3. 校验房主并绑定删除逻辑
function initRoomOwnerActions(roomId, userId, deleteBtnId, redirectUrl) {
    const deleteRoomBtn = document.getElementById(deleteBtnId);
    if (!deleteRoomBtn) return;
    fetch(`/api/rooms/${roomId}`)
        .then(response => response.json())
        .then(room => {
            if (room.creator_id === userId) {
                deleteRoomBtn.classList.remove('hidden');
            }
        });
    deleteRoomBtn.addEventListener('click', () => {
        if (confirm('确定要删除该房间吗？')) {
            fetch(`/api/rooms/${roomId}`, {
                method: 'DELETE',
                headers: { 'X-User-Id': userId }
            })
            .then(response => {
                if (response.ok) {
                    window.location.href = redirectUrl;
                } else {
                    throw new Error('删除房间失败');
                }
            })
            .catch(error => {
                showToast('删除房间失败: ' + error.message, 'error');
            });
        }
    });
}

// 4. Tab切换/Panel显示
function switchPanel(panelId, allPanelIds) {
    allPanelIds.forEach(id => {
        const el = document.getElementById(id);
        if (el) el.classList.add('hidden');
    });
    const showEl = document.getElementById(panelId);
    if (showEl) showEl.classList.remove('hidden');
}

// 5. 创建并进入游戏房间
function createAndEnterGameRoom(gameName, page, user) {
    if (!user) {
        showToast('请先登录', 'error');
        return;
    }
    fetch('/api/rooms', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-User-Id': user.userId,
            'X-User-Name': encodeURIComponent(user.username)
        },
        body: JSON.stringify({ name: gameName, tag: 'game' })
    })
    .then(res => {
        if (!res.ok) throw new Error('创建房间失败');
        return res.json();
    })
    .then(data => {
        window.location.href = `/static/${page}?room_id=${data.room_id}`;
    })
    .catch(() => {
        showToast('创建房间失败，请重试', 'error');
    });
}

// 6. 加载骨架屏动画
function showSkeleton(containerId, count = 3) {
    const container = document.getElementById(containerId);
    if (!container) return;
    container.innerHTML = '';
    for (let i = 0; i < count; i++) {
        const skeleton = document.createElement('div');
        skeleton.className = 'bg-gray-200 rounded-xl h-12 mb-2 animate-pulse';
        container.appendChild(skeleton);
    }
}

// 7. 退出登录并跳转
function logoutAndRedirect(redirectUrl = '/static/profile.html') {
    localStorage.removeItem('gozero_chat_user');
    window.location.href = redirectUrl;
}

// 8. 统计在线人数（示例）
function fetchOnlineCounts(cb) {
    fetch('/api/online-users')
        .then(res => res.json())
        .then(data => {
            if (cb) cb(data.count);
        })
        .catch(() => {
            if (cb) cb(0);
        });
}

// 9. 统一本地存储key
const USER_STORAGE_KEY = 'gozero_chat_user'; 

// 10. 通用游戏房间用户管理与准备状态逻辑
function initGameRoomUserManager(options) {
    // options: { roomId, userId, userName, readyBtnId, playerCardIds, playerNameIds, playerStatusIds, roomUserCountId, onAllReady }
    const {
        roomId, userId, userName,
        readyBtnId = 'ready-btn',
        playerCardIds = ['player1-card', 'player2-card'],
        playerNameIds = ['player1-name', 'player2-name'],
        playerStatusIds = ['player1-status', 'player2-status'],
        roomUserCountId = 'room-user-count',
        onAllReady
    } = options;
    
    let players = [];
    let myReady = false;
    let ws = null;
    let wsUrl = `ws://${location.host}/ws?user_id=${userId}&user_name=${encodeURIComponent(userName)}&room_id=${roomId}`;
    let wsReconnectTimer = null;
    let lastUserData = null;

    // --- 本地缓存key ---
    const readyKey = `game_ready_${roomId}_${userId}`;
    const playersKey = `game_players_${roomId}`;

    // --- 本地缓存 ---
    function saveReadyStatusToLocalStorage(userId, ready) {
        try {
            localStorage.setItem(readyKey, ready ? "true" : "false");
        } catch {}
    }
    function loadReadyStatusFromLocalStorage(userId) {
        try {
            const savedStatus = localStorage.getItem(readyKey);
            if (savedStatus !== null) return savedStatus === "true";
        } catch {}
        return false;
    }
    function savePlayersToLocalStorage() {
        try {
            localStorage.setItem(playersKey, JSON.stringify(players));
        } catch {}
    }
    function loadPlayersFromLocalStorage() {
        try {
            const savedPlayers = localStorage.getItem(playersKey);
            if (savedPlayers) {
                const parsedPlayers = JSON.parse(savedPlayers);
                if (Array.isArray(parsedPlayers) && parsedPlayers.length > 0) {
                    players = parsedPlayers;
                    return true;
                }
            }
        } catch {}
        return false;
    }

    // --- UI刷新 ---
    function updatePlayersUI() {
        if (roomUserCountId) {
            const el = document.getElementById(roomUserCountId);
            if (el) el.textContent = `房间人数：${players.length}`;
        }
        for (let i = 0; i < playerCardIds.length; i++) {
            const card = document.getElementById(playerCardIds[i]);
            const nameEl = document.getElementById(playerNameIds[i]);
            const statusEl = document.getElementById(playerStatusIds[i]);
            if (players.length > i) {
                const p = players[i];
                if (nameEl) nameEl.textContent = p.user_name || '未知玩家';
                if (statusEl) {
                    statusEl.textContent = p.ready ? '已准备' : '未准备';
                    statusEl.className = `status${p.ready ? ' ready' : ''}`;
                }
                if (card) {
                    card.className = `player-card${p.ready ? ' ready' : ' not-ready'}`;
                    card.setAttribute('data-user-id', p.user_id);
                }
                if (p.user_id === userId) {
                    myReady = p.ready;
                    const readyBtn = document.getElementById(readyBtnId);
                    if (readyBtn) readyBtn.textContent = myReady ? '取消准备' : '准备';
                }
            } else {
                if (nameEl) nameEl.textContent = '等待加入...';
                if (statusEl) {
                    statusEl.textContent = '未准备';
                    statusEl.className = 'status';
                }
                if (card) {
                    card.className = 'player-card not-ready';
                    card.removeAttribute('data-user-id');
                }
            }
        }
        // 检查所有玩家是否准备好
        if (typeof onAllReady === 'function') {
            if (players.length > 1 && players.every(p => p.ready)) {
                onAllReady(players);
            }
        }
        savePlayersToLocalStorage();
    }

    // --- 拉取用户列表 ---
    async function fetchRoomUsers() {
        try {
            const response = await fetch(`/api/rooms/users?room_id=${roomId}`);
            if (!response.ok) throw new Error('获取房间用户列表失败');
            const users = await response.json();
            if (Array.isArray(users)) {
                // 保留本地ready状态
                const readyStatusMap = {};
                players.forEach(p => { readyStatusMap[p.user_id] = p.ready; });
                players = users.map(u => ({
                    user_id: u.user_id,
                    user_name: u.user_name,
                    join_time: u.join_time || Date.now(),
                    ready: readyStatusMap[u.user_id] || u.ready || false
                }));
                players.sort((a, b) => a.join_time - b.join_time);
            }
            return players;
        } catch {
            return players;
        }
    }
    function forceUpdateRoomUsers() {
        fetchRoomUsers().then(updatePlayersUI);
    }
    // --- 更新玩家准备状态 ---
    function updatePlayerReadyStatus(userId, isReady) {
        const player = players.find(p => p.user_id === userId);
        if (player) player.ready = isReady;
        updatePlayersUI();
    }

    // --- WebSocket连接 ---
    function connectGameRoomWS() {
        if (ws) { ws.close(); ws = null; }
        ws = new WebSocket(wsUrl);
        ws.onopen = function() {
            forceUpdateRoomUsers();
        };
        ws.onmessage = function(e) {
            let msg = {};
            try { msg = JSON.parse(e.data); } catch { return; }
            if (msg.type === 102) {
                try {
                    const data = JSON.parse(msg.content);
                    if (data && data.user_id && data.ready !== undefined) {
                        updatePlayerReadyStatus(data.user_id, data.ready);
                        return;
                    }
                } catch {}
            }
            if ([100, 101, 102, 1, 2].includes(msg.type)) {
                setTimeout(forceUpdateRoomUsers, 100);
            }
        };
        ws.onclose = function() {
            if (wsReconnectTimer) clearTimeout(wsReconnectTimer);
            wsReconnectTimer = setTimeout(connectGameRoomWS, 3000);
        };
        ws.onerror = function(error) {
            console.error('WebSocket错误:', error);
            showToast('连接出错，正在重试...', 'error');
        };
    }
    connectGameRoomWS();

    // --- 准备按钮逻辑 ---
    const readyBtn = document.getElementById(readyBtnId);
    if (readyBtn) {
        readyBtn.onclick = function() {
            myReady = !myReady;
            updatePlayerReadyStatus(userId, myReady);
            saveReadyStatusToLocalStorage(userId, myReady);
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({
                    type: 100,
                    content: JSON.stringify({ op: 'ready', ready: myReady, user_id: userId, user_name: userName })
                }));
            }
        };
    }

    // --- 初始化 ---
    // 加载本地准备状态
    const localReadyStatus = loadReadyStatusFromLocalStorage(userId);
    if (localReadyStatus !== null) myReady = localReadyStatus;
    // 先尝试本地缓存
    if (!loadPlayersFromLocalStorage()) {
        forceUpdateRoomUsers();
    } else {
        updatePlayersUI();
        setTimeout(forceUpdateRoomUsers, 500);
    }
    // 定时刷新
    setInterval(forceUpdateRoomUsers, 5000);
} 

// 通用安全关闭 WebSocket 并跳转
function safeCloseWSAndGo(url) {
    if (window.ws) { try { window.ws.close(); } catch(e) {} window.ws = null; }
    window.location.href = url;
}

// 11. 好友相关功能
const FriendService = {
    // 添加好友
    addFriend: function(friendId) {
        const user = getCurrentUser();
        if (!user) {
            showToast('请先登录', 'error');
            return Promise.reject('未登录');
        }

        // 验证friendId参数
        if (!friendId || friendId.trim() === '') {
            showToast('请输入好友ID', 'error');
            return Promise.reject('好友ID不能为空');
        }

        // 防止添加自己为好友
        if (friendId === user.userId) {
            showToast('不能添加自己为好友', 'error');
            return Promise.reject('不能添加自己为好友');
        }

        return new Promise((resolve, reject) => {
            fetch('/api/friends', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-User-Id': user.userId,
                    'X-User-Name': encodeURIComponent(user.username)
                },
                body: JSON.stringify({ friend_id: friendId.trim() })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('添加好友失败，状态码: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showToast('添加好友成功');
                    resolve(data);
                } else {
                    throw new Error('添加失败: ' + (data.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('添加好友失败:', error);
                showToast('添加好友失败: ' + error.message, 'error');
                reject(error);
            });
        }); // 添加缺失的括号
    },

    // 搜索好友
    searchFriends: function(term) {
        const user = getCurrentUser();
        if (!user) {
            showToast('请先登录', 'error');
            return Promise.reject('未登录');
        }

        // 添加空值检查
        if (!term || term.trim() === '') {
            return Promise.resolve([]);
        }

        return new Promise((resolve, reject) => {
            fetch(`/api/friends/search?term=${encodeURIComponent(term.trim())}`, {
                headers: {
                    'X-User-Id': user.userId
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('搜索好友失败，状态码: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                resolve(data.friends || []);
            })
            .catch(error => {
                console.error('搜索好友失败:', error);
                showToast('搜索好友失败，请重试', 'error');
                reject(error);
            });
        }); // 添加缺失的括号
    },

    // 加载好友列表
    loadFriendsList: function() {
        const user = getCurrentUser();
        if (!user) {
            return Promise.reject('未登录');
        }

        return new Promise((resolve, reject) => {
            fetch('/api/friends', {
                headers: {
                    'X-User-Id': user.userId
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('加载好友列表失败');
                }
                return response.json();
            })
            .then(data => {
                resolve(data.friends || []);
            })
            .catch(error => {
                console.error('加载好友列表失败:', error);
                reject(error);
            });
        });
    }
};